package com.cat.binaryTree;

import java.util.HashSet;

/**
 * @author 曲大人的喵
 * @description https://leetcode.cn/problems/sum-of-nodes-with-even-valued-grandparent/description/
 * @create 2025/9/10 10:39
 * @since JDK17
 */

public class Solution11 {
    HashSet<Integer> set = new HashSet<>();
    int dfs(TreeNode root, int depth) {
        if (root == null) {
            return 0;
        }
        int ans = 0;
        if (set.contains(depth)) {
            ans = root.val;
        }
        if (root.val % 2 == 0) {
            set.add(depth + 2);
        }
        ans += dfs(root.left, depth + 1);
        ans += dfs(root.right, depth + 1);
        set.remove(depth + 2);
        return ans;
    }
    public int sumEvenGrandparent(TreeNode root) {
        return dfs(root, 0);
    }
}
